import React, { useEffect, useRef, useState } from 'react';
import './ShortcutInput.css';

interface ShortcutInputProps {
  value: string;
  onChange: (shortcut: string) => void;
  onValidate?: (shortcut: string) => Promise<{ valid: boolean; message: string }>;
  disabled?: boolean;
  placeholder?: string;
}

const ShortcutInput: React.FC<ShortcutInputProps> = ({
  value,
  onChange,
  onValidate,
  disabled = false,
  placeholder = '点击录制快捷键...'
}) => {
  const [isRecording, setIsRecording] = useState(false);
  const [recordedKeys, setRecordedKeys] = useState<string[]>([]);
  const [validationStatus, setValidationStatus] = useState<{ valid: boolean; message: string } | null>(null);
  const [isValidating, setIsValidating] = useState(false);
  const inputRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (value && onValidate) {
      validateShortcut(value);
    }
  }, [value]);

  const validateShortcut = async (shortcut: string) => {
    if (!onValidate) return;
    
    setIsValidating(true);
    try {
      const result = await onValidate(shortcut);
      setValidationStatus(result);
    } catch (error) {
      setValidationStatus({ valid: false, message: '验证失败' });
    } finally {
      setIsValidating(false);
    }
  };

  const normalizeKey = (key: string): string => {
    const keyMap: { [key: string]: string } = {
      'Control': 'Ctrl',
      'Meta': window.electronAPI?.platform === 'darwin' ? 'Cmd' : 'Win',
      'ArrowUp': 'Up',
      'ArrowDown': 'Down',
      'ArrowLeft': 'Left',
      'ArrowRight': 'Right',
      ' ': 'Space',
      'Escape': 'Escape',
      'Enter': 'Enter',
      'Tab': 'Tab',
      'Backspace': 'Backspace',
      'Delete': 'Delete',
      'Home': 'Home',
      'End': 'End',
      'PageUp': 'PageUp',
      'PageDown': 'PageDown',
      'Insert': 'Insert'
    };
    
    return keyMap[key] || key;
  };

  const getElectronShortcut = (keys: string[]): string => {
    const modifiers: string[] = [];
    const regularKeys: string[] = [];
    
    keys.forEach(key => {
      if (['Ctrl', 'Alt', 'Shift', 'Cmd', 'Win'].includes(key)) {
        if (key === 'Ctrl' || key === 'Win') {
          if (!modifiers.includes('CommandOrControl')) {
            modifiers.push('CommandOrControl');
          }
        } else if (key === 'Cmd') {
          if (!modifiers.includes('Command')) {
            modifiers.push('Command');
          }
        } else {
          if (!modifiers.includes(key)) {
            modifiers.push(key);
          }
        }
      } else {
        if (!regularKeys.includes(key)) {
          regularKeys.push(key);
        }
      }
    });
    
    // 排序修饰键以保持一致性
    const sortedModifiers = modifiers.sort((a, b) => {
      const order = ['CommandOrControl', 'Command', 'Control', 'Alt', 'Shift'];
      return order.indexOf(a) - order.indexOf(b);
    });
    
    return [...sortedModifiers, ...regularKeys].join('+');
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (!isRecording || disabled) return;
    
    e.preventDefault();
    e.stopPropagation();
    
    const key = normalizeKey(e.key);
    const newKeys: string[] = [];
    
    // 添加修饰键
    if (e.ctrlKey || e.metaKey) {
      if (window.electronAPI?.platform === 'darwin' && e.metaKey) {
        newKeys.push('Cmd');
      } else {
        newKeys.push('Ctrl');
      }
    }
    if (e.altKey) newKeys.push('Alt');
    if (e.shiftKey) newKeys.push('Shift');
    
    // 检查是否是纯修饰键按下（没有其他键）
    const isModifierOnly = ['Control', 'Alt', 'Shift', 'Meta', 'Ctrl', 'Cmd', 'Win'].includes(key);
    
    if (isModifierOnly) {
      // 只更新显示的键，但不完成录制
      setRecordedKeys(newKeys);
      return;
    }
    
    // 添加主键
    newKeys.push(key);
    setRecordedKeys(newKeys);
    
    // 验证是否有有效的组合键（至少需要一个修饰键）
    const hasModifier = newKeys.some(k => ['Ctrl', 'Alt', 'Shift', 'Cmd'].includes(k));
    if (!hasModifier) {
      // 如果没有修饰键，显示提示但不完成录制
      setValidationStatus({ valid: false, message: '请使用组合键（需要包含 Ctrl/Cmd、Alt 或 Shift）' });
      return;
    }
    
    // 完成录制并应用快捷键
    const shortcut = getElectronShortcut(newKeys);
    setIsRecording(false);
    onChange(shortcut);
    
    if (inputRef.current) {
      inputRef.current.blur();
    }
  };

  const handleStartRecording = () => {
    if (disabled) return;
    
    setIsRecording(true);
    setRecordedKeys([]);
    setValidationStatus(null);
    
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  const handleStopRecording = () => {
    setIsRecording(false);
    setRecordedKeys([]);
  };

  const handleClear = () => {
    onChange('');
    setValidationStatus(null);
    setRecordedKeys([]);
  };

  const displayShortcut = isRecording 
    ? (recordedKeys.length > 0 ? recordedKeys.join(' + ') : '请按下快捷键组合...')
    : (value || placeholder);

  const getStatusClass = () => {
    if (isValidating) return 'validating';
    if (!validationStatus) return '';
    return validationStatus.valid ? 'valid' : 'invalid';
  };

  const formatDisplayShortcut = (shortcut: string): string => {
    if (!shortcut || shortcut === placeholder) return shortcut;
    
    // 将 Electron 格式转换为显示格式
    return shortcut
      .replace(/CommandOrControl/g, window.electronAPI?.platform === 'darwin' ? 'Cmd' : 'Ctrl')
      .replace(/\+/g, ' + ');
  };

  return (
    <div className="shortcut-input-container">
      <div
        ref={inputRef}
        className={`shortcut-input ${isRecording ? 'recording' : ''} ${getStatusClass()} ${disabled ? 'disabled' : ''}`}
        tabIndex={disabled ? -1 : 0}
        onClick={handleStartRecording}
        onKeyDown={handleKeyDown}
        onBlur={handleStopRecording}
      >
        <span className="shortcut-display">
          {formatDisplayShortcut(displayShortcut)}
        </span>
        
        {isRecording && (
          <div className="recording-indicator">
            <span className="recording-dot"></span>
            <span className="recording-text">录制中...</span>
          </div>
        )}
        
        {!isRecording && value && (
          <button
            className="clear-btn"
            onClick={(e) => {
              e.stopPropagation();
              handleClear();
            }}
            disabled={disabled}
            title="清空"
          >
            ✕
          </button>
        )}
      </div>
      
      {validationStatus && (
        <div className={`validation-message ${validationStatus.valid ? 'success' : 'error'}`}>
          <span className="validation-icon">
            {isValidating ? '⏳' : validationStatus.valid ? '✅' : '❌'}
          </span>
          <span className="validation-text">{validationStatus.message}</span>
        </div>
      )}
      
      <div className="shortcut-help">
        <small>
          支持组合键：Ctrl/Cmd + Alt + Shift + 字母/数字/F1-F12/方向键等
          <br />
          示例：Ctrl+S、Cmd+Shift+A、Alt+F4
        </small>
      </div>
    </div>
  );
};

export default ShortcutInput;